package com.x.erp.manage;

import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.x.erp.dao.CarImageDao;
import com.x.erp.model.CarImage;
import com.x.framework.manage.BaseManage;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * 
 * 车辆图片服务
 * @author pansong
 *
 */
@Service
public class CarImageManage extends BaseManage {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private CarImageDao carImageDao;// 车图片服务Dao
	
	@Autowired
	private FastFileStorageClient fdfsClient;// 文件服务

	/**
	 * 
	 * 根据图片id或者图片id集合删除图片
	 * @param carImage
	 * @return
	 */
	public int deleteCarImage(CarImage carImage) throws Exception {
		int res = 0;
		// 根据imageId删除车辆图片
		if(StringUtils.isNotEmpty(carImage.getImageId())){
			res += deleteCarImageAndFDFSFile(carImage);
		}
		// 根据imageIds集合删除车辆图片
		String[] imageIds = carImage.getImageIds();
		if(imageIds != null && imageIds.length > 0){
			for (String imageId : imageIds) {
				carImage.setImageId(imageId);
				res += deleteCarImageAndFDFSFile(carImage);
			}
		}
		return res;
	}

	private int deleteCarImageAndFDFSFile(CarImage carImage) throws Exception {
		int res = 0;
		// 根据图片信息查询单张图片信息
		CarImage selecCarImage = carImageDao.selectCarImage(carImage);
		if(selecCarImage != null){
			//判断是否为首图，若为首图，直接返回0
			if(selecCarImage.getImageKey().equals("left_anterior")){
				return res;
			}
			//删除数据库车辆图片信息
			res += this.delete(selecCarImage);
			// 删除文件库图片信息
			String imageUrl = selecCarImage.getImageUrl();
			try {
				if(StringUtils.isNotEmpty(imageUrl)){
					fdfsClient.deleteFile(imageUrl);// 删除图片文件
				}
			} catch (Exception e) {
				logger.error("删除车辆，删除图片文件出错", e);
			}
		}
		return res;
	}

}
